import { join } from 'node:path';
import { Module } from '@nestjs/common';
import { ElectronModule } from '@doubleshot/nest-electron';
import { BrowserWindow, Menu, Tray, app, ipcMain, session, shell, globalShortcut } from 'electron';
import { HttpModule } from '@nestjs/axios';

import {
  ConfigModule,
  // ConfigService
} from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
// import { connectInitFn } from './../plc/childProcess'
// import { connectOptionsList } from './../plc/dataOptions/options'
import { IpcController } from './ipc.controller';
import { IpcService } from './ipc.service';
import SysOperationLog from '@main/entities/service/admin/sys/sys-operation-log.entity';

const logoPath = app.isPackaged
  ? join(app.getAppPath(), 'dist/render/logo.png')
  : join(__dirname, '../../src/render/public/logo.png');

// console.log(join(app.getAppPath(), 'dist/render/logo.png'));

const languageObj = {
  zh: {
    logout: '退出',
    label: '印刷机生管系统',
    title: '印刷机生管系统',
  },
  en: {
    logout: 'logout',
    label: 'Printing Machine Management System',
    title: 'Printing Machine Management System',
  },
  ru: {
    logout: '退出[[ru]]',
    label: '印刷机生管系统[[ru]]',
    title: '印刷机生管系统[[ru]]',
  },
};

let tray: any = null; // 在外面创建tray变量，防止被自动删除，导致图标自动消失
let win: BrowserWindow | null | any = null;
let langVal = 'zh';

// // 获取单例锁
// if (!app.requestSingleInstanceLock()) {
//   // 如果获取失败，说明已经有一个实例在运行，我们直接退出应用。
//   app.quit()
//   process.exit(0)
// }

let mainWindow = null;

async function createWindow() {
  // Create the browser window.
  const isDev = !app.isPackaged;

  mainWindow = new BrowserWindow({
    title: '东方合智-印刷机生管系统',
    icon: logoPath,
    // width: 1920,
    // height: 1080,
    // minWidth: 900,
    // minHeight: 670,
    // resizable: false,
    show: false,
    autoHideMenuBar: true,
    // frame: false,
    // ...({}),
    webPreferences: {
      contextIsolation: true,
      // nodeIntegration: true,
      // sandbox: false,
      preload: join(__dirname, '../preload/index.js'),
    },
  });

  mainWindow.maximize();

  mainWindow.on('ready-to-show', () => {
    mainWindow.show();
  });

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url);
    return { action: 'deny' };
  });

  // mainWindow.webContents.openDevTools();
  const URL = isDev
    ? 'http://localhost:5173'
    : `file://${join(app.getAppPath(), 'dist', 'render')}/index.html`;
  mainWindow.loadURL(URL);
  // isDev && mainWindow.webContents.openDevTools()

  // if (isDev) {
  //   let time = setTimeout(() => {
  //     mainWindow.webContents.openDevTools();

  //     clearTimeout(time);
  //   }, 10000);
  // }
  // if (isDev) {
  //   // mainWindow.loadURL(process.env.DS_RENDERER_URL)
  //   mainWindow.webContents.openDevTools();
  // } else {
  //   // mainWindow.loadFile(join(app.getAppPath(), 'dist/render/index.html'))
  //   // mainWindow.loadFile(`file://${join(app.getAppPath(), 'dist/render/index.html')}`)
  // }

  mainWindow.on('maximize', () => {
    mainWindow.webContents.send('maximize');
  });

  mainWindow.on('unmaximize', () => {
    mainWindow.webContents.send('unmaximize');
  });

  // 当点击关闭按钮
  mainWindow.on('close', (e) => {
    e.preventDefault(); // 阻止退出程序
    mainWindow?.setSkipTaskbar(true); // 取消任务栏显示
    mainWindow?.hide(); // 隐藏主程序窗口
  });

  mainWindow.on('show', () => {
    mainWindow?.setSkipTaskbar(false); // 在任务栏显示
  });

  if (!isDev) {
    mainWindow.setMenu(null);

    mainWindow.once('ready-to-show', () => {
      mainWindow.webContents.openDevTools();
    });
  }

  globalShortcut.register('CommandOrControl+F12', () => {
    // 获取当前窗口
    // Open devTool if the app is not packaged
    mainWindow.webContents.openDevTools();
    console.log('打开控制台');
    // BrowserWindow.getFocusedWindow().webContents.openDevTools();
  });

  setContextMenuFn();

  // 创建任务栏图标
  // tray = new Tray(isDev ? join('logo.png') : join(app.getAppPath(), 'dist/render/favicon.ico'));
  tray = new Tray(logoPath);

  // 点击托盘图标，显示主窗口
  tray?.on('click', () => {
    mainWindow?.show();
  });

  globalShortcut.register('CommandOrControl+F5', () => {
    // 获取当前窗口
    // Open devTool if the app is not packaged
    mainWindow.loadURL(URL);
  });

  win = mainWindow;

  // const { clickFn } = await connectInitFn(connectOptionsList, win)

  // ipcMain.on('plcClick', (_event, data) => {
  //   clickFn(data)
  // })

  return { win };
}

function setContextMenuFn() {
  session.defaultSession.cookies.get({}).then((cookies) => {
    const isSet = !cookies.every((item: any) => {
      const { name = null, value = null } = item;

      if (name === 'LANGUAGE' && value) {
        langVal = value || 'zh';

        initContextMenuFn();

        return false;
      }

      return true;
    });

    if (!isSet) initContextMenuFn();
  });
}

function initContextMenuFn() {
  // 自定义托盘图标的内容菜单
  const contextMenu = Menu.buildFromTemplate([
    {
      // 点击退出菜单退出程序
      label: languageObj[langVal].logout,
      // icon: !app.isPackaged ? join(`./build/icon/node.png`) : join(process.resourcesPath, `app.asar.unpacked/build/icon/node.png`),
      async click() {
        // console.log(win)
        win?.destroy();
        app.quit();
      },
    },
  ]);

  tray?.setToolTip(languageObj[langVal].label); // 设置鼠标指针在托盘图标上悬停时显示的文本

  tray?.setContextMenu(contextMenu); // 设置图标的内容菜单
}

export const getMainWinFn = () => {
  return {
    mainWindow,
    ipcMain,
  };
};

@Module({
  imports: [
    HttpModule.register({
      timeout: 60000 * 5,
      maxRedirects: 5,
    }),
    ElectronModule.registerAsync({
      isGlobal: true,
      useFactory: () => createWindow(),
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule, SysOperationLog],
      useFactory: () => ({
        autoLoadEntities: true,
        type: 'better-sqlite3',
        database: `${app.getPath('userData')}/Sqlite/mydb.sqlite`,
        entities: [`${__dirname}/**/*.entity{.ts,.js}`],
        synchronize: true,
        // extra: {
        //   timezone: configService.get('database.timezone'), // 时区
        //   useUTC:true
        // },
        // timezone: configService.get('database.timezone'), // 时区
      }),
    }),
    TypeOrmModule.forFeature([
      SysOperationLog,
    ]),
  ],
  controllers: [IpcController],
  providers: [IpcService],
  exports: [HttpModule, TypeOrmModule],
})
export class IpcModule {}


